import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;

import org.omg.CORBA.Environment;


public class JMessenger {

	private NetworkManager networkManager=NetworkManager.getInstance();
	
	public static void main(String[] args) {		
		JMessenger j=new JMessenger();
		j.start();		
	}
	
	public JMessenger(){		
	}
	
	public void start(){
		System.out.println("JMessenger started");
		
				
		networkManager.initialize();
		//showHelp();
		
		do{
			
			receiveUserCommand();			
			
		}while(true);
			
		
	}
	
	private void receiveUserCommand(){		
		String cmd=Utility.promptInput("Please enter command character (enter h for help)...");
		char c=(cmd.length()>0)? cmd.charAt(0):'x';
		switch(c){
		case 'h': {showHelp(); break;}
		case 's': {send(); break;}
		case 'a': {sendAll(); break;}
		case 'u': {showUserList(); break;}
		case 'e': {stop(); break;}
		default: {
			System.out.println("Invalid command. Please enter valid command character shown below.");
			showHelp();
			break;
			}
		}
		
		
	}
	
	private void showHelp(){
		String msg="---------------------------------------------\n";
		msg+="Command List\n";
		msg+="---------------------------------------------\n";
		msg+="1. Enter \"h\" to view this command list.\n";
		msg+="2. Enter \"s\" to send message to a user.\n";
		msg+="3. Enter \"a\" to send message to all users.\n";
		msg+="4. Enter \"u\" to view user list.\n";
		msg+="5. Enter \"e\" to exit from JMessenger.\n";
		msg+="---------------------------------------------";
		System.out.println(msg);
	}
	
	private void showUserList(){
		int i=0;
		String users="";
		for(User u:NetworkManager.getInstance().getUsers()){
			users+= "\n" + ++i + ". " + u.getNickName();
		}
		
		String msg="---------------------------------------------\n";
		msg+="User List\n";
		msg+="---------------------------------------------";
		msg+=users;
		msg+="\n---------------------------------------------";
		System.out.println(msg);
	}
	
	private void send(){
		String nickName=Utility.promptInput("Please enter recipient Nick Name...");
		User u=NetworkManager.getInstance().getUser(nickName);
		if(u!=null){
			if(u.getNickName().equals(Utility.getNickName())){
				System.out.println("Cannot send message to same user.");
			}else{
				String strMsg=Utility.promptInput("Please enter your message");
				//Send the message
				networkManager.send(u,strMsg);
			}
		}else{
			System.out.println("Invalid Nick Name.");
		}
	}
	
	private void sendAll(){
		String strMsg=Utility.promptInput("Please enter your message");
		networkManager.sendAll(strMsg);
	}
	
	public void stop(){		
		System.out.println("JMessenger exit.");
		System.exit(0);
	}
	
	
	
	

}
